<template>
  <Dialog v-model="crmVisible" width="1000px" :close-on-click-modal="false" :append-to-body="true">
    <template #title>
      <div class="text-18px color-#172b4d">
        {{ edit_id ? '编辑场景' : '新建场景' }}
      </div>
    </template>
    <div class="scene-name-container">
      <div class="scene-name color=#17264d">场景名称</div>
      <el-input
        v-model.trim="formData.saveName"
        :maxlength="10"
        class="scene-input"
        placeholder="请输入场景名称,最多10个字符"
      />
    </div>
    <div class="scene-name-container">
      <div class="scene-name !color=#17264d">排序</div>
      <el-input-number
        style="width: 200px"
        :min="0"
        :max="9999"
        :step="1"
        v-model="formData.sort"
        placeholder="请输入级别"
      />
    </div>
    <div class="scene-name !color=#17264d">筛选条件</div>
    <el-form id="scene-filter-container" class="filter-container">
      <el-form-item>
        <template v-for="(formItem, index) in form" :key="formItem.fieldType + index">
          <el-row class="w-100%">
            <el-col :span="8">
              <el-select
                v-model="formItem.field"
                placeholder="请选择要筛选的字段名"
                @change="fieldChange(formItem, index)"
              >
                <el-option
                  v-for="(item, idx) in fieldList"
                  :key="idx"
                  :label="item.fieldName"
                  :value="item.field"
                />
              </el-select>
            </el-col>

            <el-col :span="1">&nbsp;</el-col>
            <el-col :span="4">
              <el-select
                @change="clearTimeValue(index)"
                v-model="formItem.condition"
                placeholder="请选择条件"
              >
                <el-option
                  v-for="item in formItem.queryTypeOption"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-col>
            <el-col :span="1">&nbsp;</el-col>
            <el-col :span="9">
              <!-- select -->
              <template v-if="formItem.fieldType == 'select'">
                <el-select
                  :multiple="formItem.condition == 'in'"
                  v-model="formItem.value"
                  placeholder="请选择筛选条件"
                >
                  <el-option
                    v-for="item in formItem.queryOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </template>
              <!-- number -->
              <template v-if="formItem.fieldType == 'number'">
                <!-- 单个 -->
                <el-input-number
                  v-if="formItem.condition != 'between'"
                  class="number-input"
                  v-model="formItem.value"
                  :min="0"
                  controls-position="right"
                />
                <!-- 区间 -->
                <template v-else>
                  <el-input-number
                    :min="0"
                    class="number-input"
                    v-model="betweenNumber"
                    controls-position="right"
                  />
                  -
                  <el-input-number
                    :min="0"
                    v-model="betweenNumber1"
                    class="number-input"
                    controls-position="right"
                  />
                </template>
              </template>
              <!-- time -->
              <template v-if="formItem.fieldType == 'time'">
                <!-- 单个时间 -->
                <el-date-picker
                  v-if="formItem.condition != 'between'"
                  v-model="formItem.value"
                  class="!w-100%"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  type="datetime"
                  placeholder="请选择时间"
                  clearable
                />
                <!-- 时间区间 -->
                <template v-else>
                  <el-date-picker
                    v-model="formItem.value"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    type="datetimerange"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    class="!w-360px"
                  />
                </template>
              </template>
              <!-- level -->
              <template v-if="formItem.fieldType == 'level'">
                <el-select
                  :multiple="formItem.condition == 'in'"
                  clearable
                  v-model="formItem.value"
                  placeholder="请选择级别"
                  class="!w-100%"
                >
                  <el-option
                    v-for="dict in resultLevel"
                    :key="dict.id"
                    :label="dict.name"
                    :value="dict.id"
                  >
                    <el-tag
                      :disable-transitions="false"
                      :style="{
                        background: dict.bgColor,
                        color: dict.textColor,
                        marginRight: '10px',
                        border: 'none',
                        cursor: 'pointer',
                        paddingRight: '9px'
                      }"
                    >
                      {{ dict.name }}
                    </el-tag>
                  </el-option>
                </el-select>
              </template>
              <!-- label -->
              <template v-if="formItem.fieldType == 'label'">
                <el-select multiple v-model="formItem.value">
                  <template v-for="group in tagList" :key="group.name">
                    <el-option disabled :label="group.name" :value="null" class="group-title" />
                    <el-option
                      v-for="item in group.labelList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    >
                      <el-tag :style="{ background: item.bgColor, color: item.textColor }">{{
                        item.name
                      }}</el-tag>
                    </el-option>
                  </template>
                </el-select>
              </template>
              <!-- area -->
              <template v-if="formItem.fieldType == 'area'">
                <el-cascader
                  @change="handleChange"
                  ref="cascaderRef"
                  v-model="formItem.value"
                  :options="areaList"
                  :props="defaultProps"
                  class="!w-260px"
                  clearable
                  style="display: table-footer-group"
                  filterable
                  placeholder="请选择所在地"
                />
              </template>
              <!-- module -->
              <template v-if="formItem.fieldType == 'module'">
                <el-select v-model="formItem.value" placeholder="请选择模块">
                  <el-option
                    v-for="item in modules"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </template>
              <!-- input -->
              <template v-if="formItem.fieldType == 'input'">
                <el-select
                  v-model="formItem.value"
                  :multiple-limit="20"
                  default-first-option
                  multiple
                  clearable
                  filterable
                  allow-create
                  placeholder="单个词不超过30字符，最多20词，回车键隔开"
                  popper-class="hidden-pop"
                />
              </template>
              <el-input
                v-if="formItem.fieldType == ''"
                v-model="formItem.value"
                placeholder="请选择左侧条件"
              ></el-input>
            </el-col>
            <el-col :span="1" class="flex items-center justify-center" style="cursor: pointer">
              <el-icon @click="handleDelete(index)"><CircleCloseFilled /></el-icon>
            </el-col>
          </el-row>
        </template>
      </el-form-item>
    </el-form>
    <p v-if="showErrors" class="el-icon-warning warning-info">
      <span class="desc">筛选条件中有重复项！</span>
    </p>
    <el-button type="text" class="!color-#172b4d" @click="handleAdd">+ 添加筛选条件</el-button>
    <template #footer>
      <el-button @click="handleCancel">取 消</el-button>
      <el-button @click="handleConfirm" type="primary" :disabled="formLoading">确 定</el-button>
    </template>
  </Dialog>
</template>

<script setup>
import * as AdvancedQueryApi from '@/api/crm/advancedQuery/index.ts'
import { CircleCloseFilled, Plus, Delete } from '@element-plus/icons-vue'
import { defaultPropsCheck, defaultProps } from '@/utils/tree'
import * as AreaApi from '@/api/system/area'
import { useCrmStore } from '@/store/modules/crm'
import * as LevelApi from '@/api/crm/customerTagConfig'
import * as customerTagApi from '@/api/crm/customerTagConfig/index'
import { customFieldHeadList } from '@/api/crm/module/index'

const message = useMessage()
/**地区*/
const areaList = ref([])

const showErrors = computed(() => {
  const result = form.value.some((item, index) => {
    return form.value.findIndex((i) => i.field == item.field) !== index
  })
  return result
})
/**字典*/
const QueryConditions = {
  eq: '等于',
  neq: '不等于',
  in: '包含',
  nin: '不包含',
  gt: '大于',
  gte: '大于等于',
  lt: '小于',
  lte: '小于等于',
  isNull: '空',
  isNotNull: '非空',
  like: '模糊查询',
  between: '范围区间'
}
// 区间
const betweenNumber = ref(0)
const betweenNumber1 = ref(0)
const form = ref([])
const crmVisible = ref(false)
const formData = ref({
  saveName: '',
  sort: 0
})
const edit_id = ref('')
/**类型*/
const crmType = ref(null)
/**各个类型的集合*/
const fieldList = ref([])

/**获取地区*/
const getAreaList = async () => {
  areaList.value = await AreaApi.getAreaTree()
}
/**湖区级别*/
const getLevel = async () => {
  resultLevel.value = await LevelApi.getLevelSimple()
}
const crmStore = useCrmStore()
const modules = computed(() => {
  return crmStore.getModules
})
/**级别列表*/
const resultLevel = ref([])
const cascaderRef = ref(null)
const handleChange = () => {
  // cascaderRef.value.togglePopperVisible(false)
}
const editTagForm = ref()
const fromTagIndex = ref(0)
/**添加搜索*/
const addPlus = (index) => {
  fromTagIndex.value = index
  editTagForm.value.open('search', null, form.value[index].value)
}
/**区间进行切换清空*/
const clearTimeValue = (index) => {
  if (form.value[index].fieldType == 'time' && form.value[index].condition != 'between') {
    form.value[index].value = 0
  } else if (form.value[index].fieldType == 'time' && form.value[index].condition == 'between') {
    form.value[index].value = []
  } else if (form.value[index].fieldType == 'select' && form.value[index].condition == 'in') {
    form.value[index].value = []
  } else if (form.value[index].fieldType == 'select' && form.value[index].condition != 'in') {
    form.value[index].value = ''
  } else if (form.value[index].fieldType == 'level' && form.value[index].condition == 'in') {
    form.value[index].value = []
  } else if (form.value[index].fieldType == 'level' && form.value[index].condition != 'in') {
    form.value[index].value = ''
  }
}
const subType = ref(null)
const tagList = ref([])
/**标签列表*/
const getTagList = async () => {
  const { list } = await customerTagApi.getCustomerTagPage()
  tagList.value = list
}
const fieldMap = {
  crm_clue: 1,
  crm_customer: 1
}
/**显示操作*/
const open = async (operaType, type, itemValue) => {
  edit_id.value = ''
  crmVisible.value = true
  subType.value = operaType
  crmType.value = type
  form.value = []
  formData.value.saveName = ''
  formData.value.sort = 0
  await getTypeCollection()
  getTagList()
  // 编辑
  if (operaType == 'edit') {
    edit_id.value = itemValue.id
    formData.value.saveName = itemValue.name
    formData.value.sort = itemValue.sort
    const obj = JSON.parse(itemValue.params)
    for (const key in obj) {
      const result = fieldList.value.find((item) => item.field == key)
      let obj2 = {
        field: result.field,
        fieldName: result.fieldName,
        fieldType: result.fieldType,
        queryOptions: result.queryOptions
          ? Object.entries(result.queryOptions).map(([value, label]) => {
              return {
                label: label,
                value: value
              }
            })
          : null,
        queryType: result.queryType,
        queryTypeOption: result.queryType.map((condition) => {
          return {
            label: QueryConditions[condition],
            value: condition
          }
        }),
        condition: obj[key].condition,
        value: null
      }
      if (obj2.fieldType == 'input') {
        if (obj2.condition == 'in') {
          obj2.value = obj[key].value
          obj2.custom = obj[key].custom
        } else {
          obj2.value = obj[key].value.split(',')
          obj2.custom = obj[key].custom
        }
      } else if (obj2.fieldType == 'number') {
        if (obj2.condition != 'between') {
          obj2.value = obj[key].value
          obj2.custom = obj[key].custom
        } else {
          obj2.custom = obj[key].custom
          betweenNumber.value = obj[key].value[0]
          betweenNumber1.value = obj[key].value[1]
        }
      } else if (obj2.fieldType == 'area') {
        if (obj2.condition == 'in') {
          obj2.value = Number(obj[key].value.join(','))
        } else {
          obj2.value = obj[key].value
        }
      } else if (obj2.fieldType == 'label') {
        if (obj2.condition == 'in') {
          obj2.value = obj[key].value
        } else {
          obj2.value = obj[key].value?.split(',').map(Number)
        }
      } else {
        obj2.value = obj[key].value
        obj2.custom = obj[key].custom
      }
      form.value.push(obj2)
    }
  } else {
    form.value.push(getItem())
  }
  getAreaList()
  getLevel()
}
defineExpose({ open })

/**获取各个类型的集合*/
const getTypeCollection = async () => {
  fieldList.value = await AdvancedQueryApi.querySceneGetConditions({ page: crmType.value })
  getFiledList()
}
/**自定义字段*/
const getFiledList = async () => {
  const fileValue = await customFieldHeadList({
    moduleId: crmStore.getModuleId,
    tableType: fieldMap[crmType.value]
  })
  const result = fileValue.filter((item) => item.isSearch == 1)
  const arr = []
  result.map((it) => {
    arr.push({
      field: it.fieldName,
      fieldName: it.name,
      fieldType: it.fieldType,
      queryOptions: it.expansion
        ? it.expansion.split(',').reduce((acc, current) => {
            const num = current
            acc[num] = num
            return acc
          }, {})
        : null,
      queryType: it.queryType,
      custom: 'custom'
    })
  })
  fieldList.value = [...fieldList.value, ...arr]
}
/**选择某一项*/
const fieldChange = (formItem, index) => {
  let obj = fieldList.value.find((item) => item.field == formItem.field)
  nextTick(() => {
    form.value[index].queryTypeOption = obj.queryType.map((condition) => {
      return {
        label: QueryConditions[condition],
        value: condition
      }
    })
    if (obj.queryOptions) {
      form.value[index].queryOptions = Object.entries(obj.queryOptions).map(([value, label]) => {
        return {
          label: label,
          value: value + ''
        }
      })
    }

    form.value[index].queryType = obj.queryType
    form.value[index].fieldType = obj.fieldType
    form.value[index].fieldName = obj.fieldName
    if (obj.custom) form.value[index].custom = obj.custom
    if (form.value[index].fieldType == 'label') {
      form.value[index].value = []
    } else {
      form.value[index].value = ''
    }
    form.value[index].condition = ''
  })
}
/**默认值*/
const getItem = () => {
  return {
    field: '',
    fieldName: '',
    fieldType: '',
    queryOptions: null,
    queryType: [],
    queryTypeOption: [],
    condition: '',
    value: ''
  }
}
/**取消*/
const handleCancel = () => {
  crmVisible.value = false
}
/**删除某一项*/
const handleDelete = async (index) => {
  await message.delConfirm()
  form.value.splice(index, 1)
}
/**添加筛选条件*/
const handleAdd = () => {
  form.value.push(getItem())
}
const formLoading = ref(false)
const emit = defineEmits(['success'])
/**确定*/
const handleConfirm = async () => {
  if (showErrors.value) {
    return
  }
  if (form.value.length == 0) {
    ElMessage.error('请检查筛选条件')
    return
  }
  if (formData.value.saveName == '') {
    ElMessage.error('请输入场景名称')
    return
  }
  const rules = form.value.some((item) => item.field === '')
  const rules2 = form.value.some((item) => item.condition === '')
  const rules3 = form.value.some(
    (item) =>
      item.value === '' ||
      item.value?.length == 0 ||
      (item.value == null && item.fieldType == 'time')
  )
  if (rules || rules2 || rules3) {
    ElMessage.error('请检查筛选条件!')
    return
  }

  // 处理
  let obj = {
    name: formData.value.saveName,
    sort: formData.value.sort,
    page: crmType.value,
    status: 1,
    params: {}
  }
  form.value.map((item) => {
    if (item.fieldType == 'input') {
      if (item.condition == 'in') {
        obj.params[item.field] = {
          condition: item.condition,
          value: item.value,
          custom: item.custom
        }
      } else {
        obj.params[item.field] = {
          condition: item.condition,
          value: item.value.join(','),
          custom: item.custom
        }
      }
    } else if (item.fieldType == 'number') {
      if (item.condition != 'between') {
        obj.params[item.field] = {
          condition: item.condition,
          value: item.value,
          custom: item.custom
        }
      } else {
        obj.params[item.field] = {
          condition: item.condition,
          value: [betweenNumber.value, betweenNumber1.value],
          custom: item.custom
        }
      }
    } else if (item.fieldType == 'area') {
      if (item.condition == 'in') {
        obj.params[item.field] = {
          condition: item.condition,
          value: [item.value]
        }
      } else {
        obj.params[item.field] = {
          condition: item.condition,
          value: item.value
        }
      }
    } else if (item.fieldType == 'label') {
      if (item.condition == 'in') {
        obj.params[item.field] = {
          condition: item.condition,
          value: item.value
        }
      } else {
        obj.params[item.field] = {
          condition: item.condition,
          value: item.value.join(',')
        }
      }
    } else {
      obj.params[item.field] = {
        condition: item.condition,
        value: item.value,
        custom: item.custom
      }
    }
  })
  try {
    formLoading.value = true
    if (subType.value == 'edit') {
      obj.id = edit_id.value
      await AdvancedQueryApi.querySceneUpdate(obj)
    } else {
      await AdvancedQueryApi.querySceneCreate(obj)
    }
    ElMessage.success('操作成功!')
    emit('success')
    crmVisible.value = false
  } finally {
    formLoading.value = false
  }
}
</script>

<style lang="scss" scoped>
.el-form-item {
  margin-bottom: 0;
}

.el-row {
  margin-bottom: 20px;
  .delete-btn {
    margin-left: 15px;
    color: #bbb;
    cursor: pointer;
  }
  .el-select,
  .el-date-editor {
    width: 100%;
  }
}

.warning-info {
  width: 100%;
  font-size: 14px;
  color: #f56c6c;
  margin-top: 10px;
  .desc {
    padding-left: 8px;
  }
}

.scene-name-container {
  padding-bottom: 15px;
  .scene-input {
    width: 300px;
  }
}
.scene-name {
  margin-bottom: 10px;
}

.distpicker-address-wrapper {
  select {
    border-radius: 2px;
    font-size: 13px;
    height: 34px;
    -webkit-appearance: none;
    background-image: url('');
    background-position: calc(100% - 4px) 50%;
    background-repeat: no-repeat;
    background-size: 5px 11px;
  }
}
</style>
